/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 2 -*- */
/**
* @file shm.cpp
* 
* Library for easy comunication aplications through IPC(shared memory segment).
* 
* @author Miguel Ángel Vílchez López 2009 <sacra@openmatica.es>
*
* Codigo is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* 
* Codigo is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License along
* with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "shm.hpp"
#include "debug.cpp"

CMShm::CMShm(long int id, unsigned long int buffer=1024,bool debug=false,const char* filename=""):debug(debug,filename)
{
	this->id = id;
	this->buffer_size=buffer;
	this->debug.debug("Trying to create the shared memory segment...");
	if((this->id = shmget((key_t)this->id,this->buffer_size, IPC_CREAT | 0666))<0)
	{ this->debug.error(strerror(errno),__FILE__,__FUNCTION__,(__LINE__)); }
}

CMShm::~CMShm()
{
}

int CMShm::read(char *data)
{
	char *shm;

	this->debug.debug("Trying to read from the shared memory segment...");
	if ((shm = (char *)shmat(this->id, 0, 0)) <(char *) 0)
	{
		this->debug.error(strerror(errno),__FILE__,__FUNCTION__,(__LINE__));
		return -1;
	}

	strncpy(data,shm,this->buffer_size);

	return strlen(shm);
}

int CMShm::write(char *data)
{
	char *shm;

	this->debug.debug("Trying to write to the shared memory segment...");
	if ((shm = (char *)shmat(this->id, 0, 0)) <(char *) 0)
	{
		this->debug.error(strerror(errno),__FILE__,__FUNCTION__,(__LINE__));
		return -1;
	}

	strncpy(shm,data,this->buffer_size);

	return 0;
}

int CMShm::del()
{
	this->debug.debug("Trying to delete the shared memory segment...");
	if(shmctl(this->id,IPC_RMID,0)==-1)
	{
		this->debug.error(strerror(errno),__FILE__,__FUNCTION__,(__LINE__));
		return -1;
	}
	return 0;
}
